package cn.maihe.elg.operation.web.promotion;

import cn.maihe.elg.operation.exception.ErrorCode;
import cn.maihe.elg.operation.exception.SystemRuntimeException;
import cn.maihe.elg.operation.model.enums.UserType;
import cn.maihe.elg.operation.model.vo.promotion.ChannelReportQueryVO;
import cn.maihe.elg.operation.model.vo.promotion.ChannelReportVO;
import cn.maihe.elg.operation.repository.entity.*;
import cn.maihe.elg.operation.security.model.UserContext;
import cn.maihe.elg.operation.service.promotion.ExtendChannelService;
import cn.maihe.elg.operation.utils.DownloadExcelTool;
import cn.maihe.elg.operation.utils.IdGenerate;
import cn.maihe.elg.operation.utils.UserContextUtil;
import cn.maihe.framework.starter.base.sql.PageBo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 推广渠道信息controller
 * @Author WJH
 * @Date 2021/03/25
 */
@Api(value = "推广渠道信息管理", tags = "推广渠道信息管理")
@RestController
@RequestMapping("/api")
@Slf4j
public class ExtendChannelController {
    @Resource
    private ExtendChannelService extendChannelService;
    @Autowired
    private DownloadExcelTool downloadExcelTool;

    @ApiOperation(value = "分页查询推广渠道信息", notes = "根据推广渠道信息名称 分页查询")
    @RequestMapping(value = "/extendChannels", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "channelName", value = "推广渠道名称", dataType = "String", paramType = "query"),
    })
    public PageBo<ExtendChannelVo> pageList(int pageNo, int pageSize, ExtendChannelVo vo) {

        UserContext uc= UserContextUtil.getUserContext();
        if(UserType.GENERAL.getType() != uc.getUserType()){
            vo.setOrgId(uc.getOrgId());
        }
        return extendChannelService.selectPageBySql(pageNo, pageSize, vo);
    }

    @ApiOperation(value = "获取推广渠道信息", notes = "根据推广渠道信息id获取推广渠道信息")
    @ApiImplicitParam(name = "id", value = "推广渠道信息id", dataType = "long", paramType = "path", required = true)
    @RequestMapping(value = "/extendChannel/{id}", method = RequestMethod.GET)
    public ExtendChannelVo getBidCustomer(@PathVariable Long id) {
        ExtendChannelVo curVO = extendChannelService.getExtendChannelDetailById(id);
        if (curVO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "推广渠道信息id");
        }
        return curVO;
    }

    @ApiOperation(value = "新增推广渠道信息", notes = "新增推广渠道信息")
    @RequestMapping(value = "/extendChannel", method = RequestMethod.POST)
    public void createExtendChannel(@Validated @RequestBody ExtendChannelVo vo) {
        // 暂无手动创建用户，不创建 valid VO
        ExtendChannelDO cDO = ExtendChannelDO.of(vo);
        cDO.setId(IdGenerate.getId());

        if (extendChannelService.exists(ExtendChannelDOCondition.builder().andInviteCodeEq(vo.getInviteCode()).build())) {
            throw new SystemRuntimeException(ErrorCode.EXISTS, "推广码", vo.getInviteCode());
        }
        UserContext uc= UserContextUtil.getUserContext();
        cDO.setOrgId(uc.getOrgId());

        extendChannelService.insert(cDO);
    }

    @ApiOperation(value = "修改推广渠道信息", notes = "根据推广渠道信息id修改推广渠道信息")
    @RequestMapping(value = "/extendChannel", method = RequestMethod.PUT)
    public void modifyExtendChannel(@Validated @RequestBody ExtendChannelVo vo) {
        // 暂无手动创建用户，不创建 valid VO
        ExtendChannelDO cDO = ExtendChannelDO.of(vo);
        Assert.notNull(vo.getId(), "推广渠道主键Id不能为空");

        if (extendChannelService.exists(ExtendChannelDOCondition.builder().andInviteCodeEq(vo.getInviteCode()).andIdNe(vo.getId()).build())) {
            throw new SystemRuntimeException(ErrorCode.EXISTS, "推广码", vo.getInviteCode());
        }

        cDO.setUserModified(UserContextUtil.getUserContext().getUsername());
        cDO.setGmtModified(new Date());

        extendChannelService.updateById(cDO);
    }

    @ApiOperation(value = "删除推广渠道信息", notes = "根据推广渠道信息id删除推广渠道信息")
    @ApiImplicitParam(name = "id", value = "推广渠道信息id", dataType = "long", paramType = "path", required = true)
    @RequestMapping(value = "/extendChannel/{id}", method = RequestMethod.DELETE)
    public void deleteBidCustomer(@PathVariable Long id) {
        extendChannelService.deleteById(id);
    }


    @ApiOperation(value = "渠道推广统计查询", notes = "渠道推广统计查询")
    @RequestMapping(value = "/channelReports", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "gmtTimeRange", value = "起始时间", dataType = "String", paramType = "query"),
    })
    public PageBo<ChannelReportVO> pageReportList(int pageNo, int pageSize, String gmtTimeRange) {
        ExtendChannelVo vo = new ExtendChannelVo();
        UserContext uc= UserContextUtil.getUserContext();
        if(UserType.GENERAL.getType() != uc.getUserType()){
            vo.setOrgId(uc.getOrgId());
        }

        return extendChannelService.selectReportPageBySql(pageNo, pageSize, gmtTimeRange, vo);
    }


    @ApiOperation(value = "渠道推广统计下载", notes = "渠道推广统计下载")
    @RequestMapping(value = "/channelReport/download", method = RequestMethod.POST)
    public void download(@Validated @RequestBody ChannelReportQueryVO vo, HttpServletResponse response) throws UnsupportedEncodingException {
        String path = "channelReport.xlsx";
        String filename = "渠道推广统计";

        UserContext uc= UserContextUtil.getUserContext();
        if(UserType.GENERAL.getType() != uc.getUserType()){
            vo.setOrgId(uc.getOrgId());
        }

        List<ChannelReportVO> lists = extendChannelService.listChannelReportDownload(vo);

        Map<String, String> map = new HashMap<>();
        map.put("gmtTime",vo.getGmtTimeRange().stream().collect(Collectors.joining(" ~ ")));

        downloadExcelTool.downloadByTemplateName(path, filename, response, lists, map);
    }

}
